package common.quartz;

import java.security.SecureRandom;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Corn表达式工具类
 */
public final class CronExpUtil {

	private static final SecureRandom numberGenerator = new SecureRandom();

	/**
	 * 生成TriggerID
	 * 
	 * @return 返回前缀加时间的ID字符串
	 */
	public static String generateID(String prefix) {
		String id = prefix;
		synchronized (numberGenerator) {
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			id += format.format(date);
		}
		return id;
	}

	/**
	 * 将日期时间转化为Corn表达式
	 * 
	 * @return Corn表达式
	 */
	public static String toCornExpr(Date time) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(time);
		int year = cal.get(Calendar.YEAR);// 获取年份
		int month = cal.get(Calendar.MONTH);// 获取月份
		int day = cal.get(Calendar.DAY_OF_MONTH);// 获取日
		int hour = cal.get(Calendar.HOUR_OF_DAY);// 小时
		int minute = cal.get(Calendar.MINUTE);// 分
		int second = cal.get(Calendar.SECOND);// 秒
		String msg = "{0,number,00} {1,number,00} {2,number,00} {3,number,00} {4,number,00} ? {5,number,0000}";
		String mf = MessageFormat.format(msg, second, minute, hour, day, month, year);
		return mf;
	}

	public static void main(String[] args) {
		System.out.println(toCornExpr(new Date()));
	}

}